package com.hhdys.action;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hhdys.annotation.Access;
import com.hhdys.model.Function;
import com.hhdys.service.FunctionService;
import com.hhdys.service.MenuTreeService;

@Controller
@RequestMapping("/admin/function")
@Access("功能管理")
public class FunctionAction {

	private static Logger log = Logger.getLogger(FunctionAction.class);
	@Autowired
	private MenuTreeService menuService;
	@Autowired
	private FunctionService service;

	@RequestMapping("/function")
	@Access("查看")
	public String showfunction(Model model) {
		model.addAttribute("tree", menuService.getMenuTreesJson());
		return "admin/menu/function";
	}

	@RequestMapping("/addFunc")
	@ResponseBody
	@Access("添加")
	public String addFunc(Function func) {
		Subject curUser = SecurityUtils.getSubject();
		func.setLastModifier((String) curUser.getPrincipal());
		func.setModifyTime(new Date());
		service.addFunction(func);
		return "success";
	}

	@RequestMapping(value="/getFuncs",produces = "application/json;charset=utf-8")
	@ResponseBody
	public String getFuncs(int id) {
		List<Function> list = service.getFunctionsByPageId(id);
		StringBuilder builder = new StringBuilder();
		builder.append("[");
		for (Function func : list) {
			builder.append("{\"id\":" + func.getId() + ",\"name\":\""
					+ func.getName() + "\"},");
		}
		if (builder.length() > 1) {
			builder.deleteCharAt(builder.length() - 1);
		}
		builder.append("]");
		return builder.toString();
	}

	@RequestMapping("/delFunc")
	@ResponseBody
	@Access("删除")
	public String delFunction(int id) {
		service.delFunction(id);
		return "success";
	}

	/**
	 * @return the menuService
	 */
	public MenuTreeService getMenuService() {
		return menuService;
	}

	/**
	 * @param menuService
	 *            the menuService to set
	 */
	public void setMenuService(MenuTreeService menuService) {
		this.menuService = menuService;
	}

	/**
	 * @return the service
	 */
	public FunctionService getService() {
		return service;
	}

	/**
	 * @param service
	 *            the service to set
	 */
	public void setService(FunctionService service) {
		this.service = service;
	}
}
